package io.gitee.zhangbinhub.acp.cloud.lock

import io.gitee.zhangbinhub.acp.boot.log.LogAdapter
import org.redisson.api.RedissonClient
import java.util.concurrent.TimeUnit

class RedisDistributedLock(
    private val logAdapter: LogAdapter,
    private val redissonClient: RedissonClient
) : DistributedLock {
    override fun getLock(
        lockId: String,
        timeOut: Long,
        reentrant: Boolean
    ): Boolean = try {
        redissonClient.getLock(lockId).let { lock ->
            if (reentrant) {
                lock.tryLock(timeOut, 0, TimeUnit.MILLISECONDS)
            } else {
                if (lock.isHeldByCurrentThread) {
                    return false
                } else {
                    lock.tryLock(timeOut, 0, TimeUnit.MILLISECONDS)
                }
            }
        }
    } catch (e: Exception) {
        logAdapter.error(e.message, e)
        false
    }

    override fun releaseLock(lockId: String) {
        try {
            redissonClient.getLock(lockId).unlock()
        } catch (e: Exception) {
            logAdapter.error(e.message, e)
        }
    }
}